package com.wanli.agent.homepage;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseActivity;
import com.wanli.agent.event.ChooseLocationEvent;
import com.wanli.agent.utils.NumberFormatUtils;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.AppTitleBar;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChooseLocationActivity extends BaseActivity implements AMap.OnCameraChangeListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    //初始化地图控制器对象
    AMap aMap;
    @BindView(R.id.mapView)
    MapView mMapView;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_longitude)
    TextView tvLongitude;
    @BindView(R.id.tv_latitude)
    TextView tvLatitude;
    //缩放级别
    private float zoom = 17f;
    //俯仰角0°~45°（垂直与地图时为0）
    private float angle = 0f;
    //偏航角 0~360° (正北方为0)
    private float yaw = 0f;
    private String detailLocation;
    private String cityName;
    private double latitude;
    private double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_location);
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
            //设置显示定位按钮 并且可以点击
            UiSettings settings = aMap.getUiSettings();
            // 是否显示定位按钮
            settings.setMyLocationButtonEnabled(false);
            aMap.setMyLocationEnabled(false);//设置为true表示启动显示定位蓝点，
            aMap.showIndoorMap(false);  //是否显示室内地图
            settings.setZoomControlsEnabled(false);//把右下角的加减号去掉
            settings.setLogoBottomMargin(-100);//隐藏logo
            aMap.setOnCameraChangeListener(this);
        }
        cityName = getIntent().getStringExtra("cityName");
        detailLocation = getIntent().getStringExtra("detailLocation");

        titleBar.setRightClickListener(() -> {
            String lat = NumberFormatUtils.formatDecimal6(latitude + "");
            String lng = NumberFormatUtils.formatDecimal6(longitude + "");
            EventBus.getDefault().post(new ChooseLocationEvent(Double.parseDouble(lat), Double.parseDouble(lng)));
            finish();
        });

        initView();
        try {
            searchAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }



        tvSearch.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(detailLocation)) {
                try {
                    searchAddress();
                } catch (AMapException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void searchAddress() throws AMapException {
        PoiSearch.Query query = new PoiSearch.Query(detailLocation, "", cityName);
        PoiSearch poiSearch = new PoiSearch(mActivity, query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int errcode) {

                //判断搜索成功
                if (errcode == 1000 && poiResult.getPois().size() > 0) {
                    LatLonPoint latLonPoint = poiResult.getPois().get(0).getLatLonPoint();
                    latitude = latLonPoint.getLatitude();
                    longitude = latLonPoint.getLongitude();

                    tvLatitude.setText("纬度：" + latitude);
                    tvLongitude.setText("经度：" + longitude);

                    changeCamera(
                            CameraUpdateFactory.newCameraPosition(new CameraPosition(
                                    new LatLng(latitude, longitude), zoom, angle, yaw)));
                } else {
                    ToastUtil.showShort("搜索不到地址");
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }

        });
        poiSearch.searchPOIAsyn();
    }

    public void initView() {
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(detailLocation)) {
                        try {
                            searchAddress();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                detailLocation = editSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(detailLocation)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
     */
    private void changeCamera(CameraUpdate update) {
        aMap.animateCamera(update);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng latLng = cameraPosition.target;
        latitude = latLng.latitude;
        longitude = latLng.longitude;
        tvLatitude.setText("纬度：" + latitude);
        tvLongitude.setText("经度：" + longitude);
    }

    @OnClick({R.id.view_cancel})
    public void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.view_cancel:
                editSearch.setText("");
                break;

        }
    }
}
